import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/cache'

// axios实例
const service = axios.create({
	baseURL: 'http://127.0.0.1:8080',
	timeout: 60000,
	headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const token = getToken()

		if (token && config.url!='/api/user/login') {
			config.headers.token = token
		}

		return config
	},
	error => {
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	async (response) => {
		const res = response.data
		// 响应成功
		if (res.code === 0) {
			return res
		}else if(res.code==401){
			location.href='/login'
			return Promise.reject('')
		}

		// 错误提示
		ElMessage.error(res.msg || '未知错误')

		return Promise.reject(new Error(res.msg || 'Error'))
	},
	error => {
		console.log(error);
	}
)

export default service;